﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using Pay.Core;

namespace Pay.Api.Controllers {
	public class BaseController : ApiController {
		/// <summary>
		/// 验证返回的错误提示
		/// </summary>
		public string ModelError {
			get {
				StringBuilder sb = new StringBuilder();
				foreach (var item in ModelState.Values) {
					foreach (var er in item.Errors) {
						if (!string.IsNullOrEmpty(er.ErrorMessage))
							sb.Append(er.ErrorMessage + ",");
						else
							sb.Append(er.Exception.Message + ",");
					}
				}
				return sb.ToString().TrimEnd(',');
			}
		}
		/// <summary>
		/// 获取以JSON（key:value)）的单参值
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="parameterName"></param>
		/// <param name="val"></param>
		/// <returns></returns>
		protected T GetJsonValue<T>(string parameterName, JObject val) {
			if (val.HasValues) return val.GetValue(parameterName).Value<T>();
			return default(T);
		}

		/// <summary>
		/// 获取表单提交来的KEY=Value
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="parameterName"></param>
		/// <param name="val"></param>
		/// <returns></returns>
		protected T GetPostValue<T>(string parameterName, T val) {
			if (val != null) return val;
			HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
			HttpRequestBase request = context.Request;//定义传统request对象            
			string value = request.Form[parameterName];

			Type type = typeof(T);
			object result;
			try {
				if (type.IsEnum)
					result = (T)Enum.Parse(type, value, true);
				else if (type == typeof(Guid) || type == typeof(Guid?)) {
					if (type == typeof(Guid))
						result = new Guid(value);
					else
						if (!string.IsNullOrEmpty(value)) result = new Guid(value);
					else result = null;
				} else {
					if (IsNullableType(type))
						result = Convert.ChangeType(value, Nullable.GetUnderlyingType(type));
					else
						result = Convert.ChangeType(value, type);
				}
			} catch {
				result = default(T);
			}
			return (T)result;
		}
		/// <summary>
		/// 获取表单提交来的KEY=Value
		/// </summary>
		/// <returns>The post value.</returns>
		/// <param name="parameterName">Parameter name.</param>
		/// <typeparam name="T">The 1st type parameter.</typeparam>
		protected T GetPostValue<T>(string parameterName) {
			HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
			HttpRequestBase request = context.Request;//定义传统request对象            
			string value = request.Form[parameterName];

			Type type = typeof(T);
			object result;
			try {
				if (type.IsEnum)
					result = (T)Enum.Parse(type, value, true);
				else if (type == typeof(Guid) || type == typeof(Guid?)) {
					if (type == typeof(Guid))
						result = new Guid(value);
					else
						if (!string.IsNullOrEmpty(value)) result = new Guid(value);
					else result = null;
				} else {
					if (IsNullableType(type))
						result = Convert.ChangeType(value, Nullable.GetUnderlyingType(type));
					else
						result = Convert.ChangeType(value, type);
				}
			} catch {
				result = default(T);
			}
			return (T)result;
		}
		/// <summary>
		/// 判断是否是Nullable类型数据
		/// </summary>
		/// <param name="theType"></param>
		/// <returns></returns>
		protected bool IsNullableType(Type theType) {
			return (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
		}
	}
}
